import { DeepPartial, FindManyOptions, UpdateResult } from "typeorm";
import { User } from "../entities";
import { AppDataSource } from "../data-source";

export class UserService {
  private static readonly userRepository = AppDataSource.getRepository(User);

  public static async create(payload: DeepPartial<User>): Promise<User> {
    const create = this.userRepository.create(payload);
    return this.userRepository.save(create);
  }

  public static async findById(id: User["id"]): Promise<User | null> {
    return this.userRepository.findOne({ where: { id } });
  }

  public static async findByName(name: User["name"]): Promise<User | null> {
    return this.userRepository.findOne({ where: { name } });
  }

  public static async find(
    options: FindManyOptions<User>,
  ): Promise<[User[], number]> {
    return this.userRepository.findAndCount(options);
  }

  public static async update(
    name: User["name"],
    payload: DeepPartial<User>,
  ): Promise<UpdateResult> {
    return this.userRepository.update({ name }, payload);
  }

  public static async remove(user: User): Promise<User> {
    return this.userRepository.remove(user);
  }
}
